/*
 * @Description:登录
 * @Author: maskMan
 * @LastEditTime: 2024-01-26 21:10:36
 */
import { jwtSign, resSend } from "../config/httpServe";
import platform from "../config/platform";
import { MonUser } from "../config/type";
import { Mondb } from "../db/mondb";
const express = require("express");
const router = express.Router();
/**网页登录返回数据 */
function _jwtSignData(user: any) {
  const data: any = {
    uid: user.uid,
    nickName: user.nickName.substring(0, 6),
    avaUrl: user.avaUrl,
  };
  user["token"] = jwtSign(data);
  return user;
}
router.get("/webLogin", async (req: any, res: any) => {
  const { uid, nickName, avaUrl } = req;
  if (uid) {
    const monUser = await Mondb.findOneUserById(uid);
    if (monUser) {
      return resSend(res, _jwtSignData(monUser), "登录成功");
    }
  }
  const userInfo = { uid, nickName, avaUrl };
  if (userInfo) {
    const monUser = Mondb.insertOneUser(userInfo as unknown as MonUser);
    if (monUser) {
      return resSend(res, _jwtSignData(monUser), "登录成功");
    }
  }
  return resSend(res, null, "登录失败", false);
});
/**h5网页登录 */
router.get("/wxH5Login", async (req: any, res: any) => {
  const { uid, code, state } = req;
  const reqData = { code: code, state: state };
  if (uid) {
    const monUser = await Mondb.findOneUserById(uid);
    if (monUser) {
      const verify = await platform.getH5ResData(reqData);
      monUser["verify"] = verify;
      return resSend(res, _jwtSignData(monUser), "登录成功");
    }
  }
  const userInfo = await platform.getH5UserInfo(code);
  if (userInfo) {
    const monUser = Mondb.insertOneUser(userInfo as unknown as MonUser);
    if (monUser) {
      const verify = await platform.getH5ResData(reqData);
      monUser["verify"] = verify;
      return resSend(res, _jwtSignData(monUser), "登录成功");
    }
  }
  return resSend(res, null, "登录失败", false);
});
export default router;
